package ui;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import model.AttributeDefinition;
import model.Customer;
import service.AttributeService;
import service.CustomerService;
import utils.CommonUtil;
import utils.PdfUtil;

import java.util.List;
import java.util.Map;

/**
 * 客户详情页面
 */
public class CustomerDetailPage extends Application {
    
    private Customer customer;
    private CustomerService customerService = new CustomerService();
    
    public CustomerDetailPage(Customer customer) {
        this.customer = customer;
        // 如果需要，可以在这里加载高亮属性信息
        loadHighlightedAttributes();
    }
    
    /**
     * 加载客户属性的高亮状态
     */
    private void loadHighlightedAttributes() {
        // 不需要额外加载，因为现在高亮状态会在CustomerService.getCustomerById时自动加载
        // 在loadCustomerAttributes方法中已经将高亮状态设置到了customer对象中
        
        // 此方法保留以保持代码兼容性
    }
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("客户详情 - " + customer.getCustomerName());
        
        VBox vbox = new VBox();
        vbox.setPadding(new Insets(10));
        vbox.setSpacing(10);
        vbox.getStyleClass().add("detail-root");
        
        // 标题 Label
        Label titleLabel = new Label("客户详情");
        titleLabel.getStyleClass().add("detail-title");
        vbox.getChildren().add(titleLabel);
        
        // 客户名称
        Label nameLabel = createDetailLabel("客户名称：", customer.getCustomerName(), false);
        vbox.getChildren().add(nameLabel);
        
        // 获取客户的属性值
        Map<Integer, String> attributeValues = customer.getAttributeValues();
        
        // 只显示客户拥有的属性
        for (Map.Entry<Integer, String> entry : attributeValues.entrySet()) {
            int attributeId = entry.getKey();
            String value = entry.getValue();
            
            // 通过attributeId获取属性定义
            AttributeDefinition attr = AttributeService.getAttributeById(attributeId);
            if (attr != null) {
                String displayName = attr.getDisplayName();
                
                // 判断是否需要高亮显示
                boolean isHighlighted = customer.isAttributeHighlighted(attributeId);
                
                Label attrLabel = createDetailLabel(displayName + "：", value, isHighlighted);
                vbox.getChildren().add(attrLabel);
            }
        }
        
        // 按钮区域
        HBox buttonBox = new HBox();
        buttonBox.setSpacing(10);
        buttonBox.setAlignment(Pos.CENTER);
        
        // 返回按钮
        Button backButton = new Button("返回");
        backButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        backButton.getStyleClass().add("button");
        backButton.setOnAction(e -> {
            CustomerListPage listPage = new CustomerListPage();
            try {
                listPage.start(new Stage());
                primaryStage.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        
        // 编辑按钮
        Button editButton = new Button("编辑");
        editButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        editButton.getStyleClass().add("button");
        editButton.setOnAction(e -> {
            // 打开编辑页面
            EditCustomerPage editPage = new EditCustomerPage(customer);
            try {
                editPage.start(new Stage());
                primaryStage.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        });
        
        // 导出PDF按钮
        Button exportPdfButton = new Button("导出PDF");
        exportPdfButton.setStyle("-fx-background-color: #5a67d8; -fx-text-fill: white; -fx-font-size: 16px; -fx-padding: 10 20;");
        exportPdfButton.getStyleClass().add("button");
        exportPdfButton.setOnAction(e -> {
            // 导出客户信息到PDF
            PdfUtil pdfUtil = new PdfUtil();
            pdfUtil.createCustomerPdf(customer);
        });
        
        buttonBox.getChildren().addAll(backButton, editButton, exportPdfButton);
        vbox.getChildren().add(buttonBox);
        
        // 滚动面板
        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setContent(vbox);
        scrollPane.setFitToWidth(true);
        scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
        scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
        
        // 设置滚动速度
        double scrollSpeed = 10.0;
        scrollPane.addEventFilter(ScrollEvent.SCROLL, event -> {
            if (event.getDeltaY() != 0) {
                double delta = event.getDeltaY() * scrollSpeed / scrollPane.getContent().getBoundsInLocal().getHeight();
                scrollPane.setVvalue(scrollPane.getVvalue() - delta);
                event.consume();
            }
        });
        
        Scene scene = new Scene(scrollPane, 1200, 900);
        scene.getStylesheets().add(getClass().getResource("/css/detail.css").toExternalForm());
        
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    /**
     * 创建详情标签
     * @param labelText 标签文本
     * @param valueText 值文本
     * @param isHighlighted 是否高亮显示
     * @return 标签对象
     */
    private Label createDetailLabel(String labelText, String valueText, boolean isHighlighted) {
        Label label = new Label(labelText + valueText);
        label.getStyleClass().add("detail-label");
        
        if (isHighlighted) {
            label.setTextFill(Color.RED);
            label.getStyleClass().add("highlighted-label");
        }
        
        return label;
    }
    
    /**
     * 显示客户详情页面
     * @param customerId 客户ID
     */
    public static void showCustomerDetail(int customerId) {
        CustomerService service = new CustomerService();
        Customer customer = service.getCustomerById(customerId);
        
        if (customer != null) {
            CustomerDetailPage detailPage = new CustomerDetailPage(customer);
            try {
                detailPage.start(new Stage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            CommonUtil.showAlert("错误", "未找到客户信息！", javafx.scene.control.Alert.AlertType.ERROR);
        }
    }
} 